package com.changgou.pay.service.impl;

import com.changgou.pay.service.WxPayService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    private WXPay wxPay;

    @Value("${wxpay.notify_url}")
    private String notify_url;

    /**
     * 统一下单服务，生成订单支付二维码等信息
     * @param orderId
     * @param money
     * @return
     */
    @Override
    public Map nativePay(String orderId, Integer money) {

        try{
            //封装数据
            Map<String,String> map = new HashMap();

            map.put("body","长颈鹿");//商品描述
            map.put("out_trade_no",orderId);//商户订单号

            BigDecimal bigDecimal = new BigDecimal("0.01");
            BigDecimal fen = bigDecimal.multiply(new BigDecimal("100"));
            fen = fen.setScale(0, BigDecimal.ROUND_UP);
            map.put("total_fee",String.valueOf(fen));//标价金额
            map.put("spbill_create_ip","127.0.0.1");//终端IP
            map.put("notify_url",notify_url);
            map.put("trade_type","NATIVE");

            //封装完参数后调用统一下单接口
            Map<String, String> mapResult = wxPay.unifiedOrder(map);

            return mapResult;


        }catch (Exception e){
            e.printStackTrace();
            return null;

        }

    }

    /**
     * 微信订单查询服务
     * @param orderId
     * @return
     */
    @Override
    public Map queryOrder(String orderId) {

        try {
            Map<String,String> map = new HashMap<>();
            map.put("out_trade_no",orderId);

            Map<String, String> result = wxPay.orderQuery(map);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public Map closeOrder(String orderId) {
        Map map=new HashMap(  );
        map.put( "out_trade_no",orderId );
        try {
            return  wxPay.closeOrder( map );
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
